const isSpiderVisitor = req => {
  let userAgent = ''
  if (
    req.headers &&
    req.headers['user-agent'] &&
    typeof req.headers['user-agent'] === 'string'
  ) {
    userAgent = req.headers['user-agent'].toLowerCase()
  }
  return ['baiduspider', 'googlebot', '360spider', 'sosospider', 'sogou'].some(
    item => (userAgent || '').includes(item)
  )
}

export default async function nuxtServerInit({ commit }, { req, route }) {
  if (!req.session) return console.error('没有session信息')
  const isSpider = isSpiderVisitor(req)
  // 保存用户位置信息
  let { city, list: cityList } = req.session.city || {}
  if (!city || !cityList.length) return
  // 城市code对应关系
  const targetCityRoute = {
    sh: 310100,
    sz: 320500
  }
  // 根据路由状态强改城市位置
  let key
  if (route.name) {
    if (route.name.includes('sh')) {
      key = 'sh'
    } else if (route.name.includes('sz')) {
      key = 'sz'
    }
  }
  // 固定城市路由
  if (key) {
    const targetCity = cityList.find(
      item => item.region_code === targetCityRoute[key]
    )
    if (targetCity) city = targetCity
  } else {
    // 是百度爬虫
    if (isSpider) {
      const targetCity = cityList.find(item => item.region_code === 320500)
      if (targetCity) city = targetCity
    }
  }
  commit('SET_INDEX', {
    city,
    cityList
  })
  // 保存用户信息
  if (req.session.authUser) {
    commit('user/SET_USER', {
      user: req.session.authUser
    })
  }
}
